﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Linq.Expressions;
using Yz.Base;
using Yz.Core.Extensions;
using Yz.DB.EFCore.Dal;
using Yz.Model.Constants;
using Yz.Model.Entities;
using Yz.Model.Enums;
using Yz.Model.Views;

namespace Yz.Web.Controllers
{
    [Authorize(Roles = UserRoleName.Admin)]
    public class CompanyController : BaseController
    {
        private readonly IDbAccess<Company> _companyDBAccess;
        private readonly IDbAccess<User> _userDbAccess;
        public CompanyController(IDbAccess<Company> companyDBAccess, IDbAccess<User> userDbAccess)
        {
            _companyDBAccess = companyDBAccess;
            _userDbAccess = userDbAccess;
        }
        public IActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 获得公司信息
        /// </summary>
        /// <param name="pageSize"></param>
        /// <param name="pageIndex"></param>
        /// <param name="name"></param>
        /// <param name="adminName"></param>
        /// <param name="statusType"></param>
        /// <returns></returns>
        public async Task<JsonResult> GetList(int pageSize, int pageIndex, string name, string adminName, StatusType statusType = StatusType.All)
        {
            var page = new ParaPage { SkipNum = (pageIndex - 1) * pageSize, TakeNum = pageSize };
            var orders = new List<ParaOrder<Company>>() {
                new ParaOrder<Company> { Order = p =>  p.UpdateTime  , IsAsc = false }
            };
            Expression<Func<Company, bool>> where = p => true;
            if (statusType != StatusType.All)
            {
                where = where.And(c => c.StatusType == statusType);
            }
            if (!name.IsEmpty())
            {
                where = where.And(c => c.Name.Contains(name));
            }
            if (!adminName.IsEmpty())
            {
                where = where.And(c => c.AdminName.Contains(adminName));
            }
            var list = await _companyDBAccess.GetListByPageAsync<VmCompany>(where, page, orders);
            return Json(list.ToVmPageList());
        }
        /// <summary>
        /// 添加修改公司
        /// </summary>
        /// <param name="company"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> Save(Company company)
        {
            if (company.Name.IsEmpty())
            {
                return Json(new VmReturn { Suc = false, Msg = "公司名称不能为空" });
            }
            if (company.AdminName.IsEmpty() || !company.AdminName.IsMobilePhone())
            {
                return Json(new VmReturn { Suc = false, Msg = "管理员账号只能是手机号" });
            }
            var retCode = ReturnCode.Fail;
            var dtNow = DateTime.Now;
            company.UpdateTime = dtNow;
            if (company.Id == 0)
            {
                if (await _userDbAccess.IsExistAsync(p => p.LoginName == company.AdminName))
                {
                    return Json(new VmReturn() { Suc = false, Msg = "您要添加的账号已存在" });
                }
                retCode = await _companyDBAccess.AddAsync(company, p => p.Name == company.Name || p.AdminName == company.AdminName);
                if (retCode == ReturnCode.Success)
                {
                    var companyInfo = await _companyDBAccess.GetModelAsync<VmCompany>(p => p.AdminName == company.AdminName);
                    await _userDbAccess.AddAsync(new User()
                    {
                        LoginName = company.AdminName,
                        LoginPwd = DefaultConstant.Password.ToMd5Hash(),
                        Name = company.AdminName,
                        UserType = UserType.CompanyAdmin,
                        CompanyId = companyInfo.Id,
                        UpdateTime = dtNow
                    }, p => p.LoginName == company.AdminName);
                }
            }
            else
            {
                retCode = await _companyDBAccess.UpdateAsync(p =>
                p.SetProperty(q => q.Name, company.Name)
                .SetProperty(q => q.StatusType, company.StatusType)
                .SetProperty(q => q.Remark, company.Remark)
                .SetProperty(q => q.UpdateTime, company.UpdateTime)
                , p => p.Id == company.Id, p => p.Id != company.Id && (p.Name == company.Name || p.AdminName == company.AdminName));
            }
            return Json(retCode.ToVmReturn());
        }
        /// <summary>
        /// 删除公司并且删除公司下所有用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> Delete(int id)
        {
            var retCode = await _companyDBAccess.DeleteAsync(p => p.Id == id);
            if (retCode == ReturnCode.Success)
            {
                await _userDbAccess.DeleteAsync(p => p.CompanyId == id);
                return Json(new VmReturn() { Suc = true, Msg = "删除成功" });
            }
            return Json(new VmReturn() { Suc = false, Msg = "删除失败" });
        }
        /// <summary>
        /// 重置管理员密码
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<JsonResult> ResetAdminPwd(int id)
        {
            string defaultPwd = DefaultConstant.Password.ToMd5Hash();
            var dtNow = DateTime.Now;
            var retCode = await _userDbAccess.UpdateAsync(p => p.SetProperty(q => q.LoginPwd, defaultPwd).SetProperty(q => q.UpdateTime, dtNow), p => p.CompanyId == id && p.UserType == UserType.CompanyAdmin);
            return Json(retCode.ToVmReturn());
        }
    }
}